<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 商品列表
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{
	
	protected $relationSearch = true;
	/**
	 * Goods模型对象
	 */
	protected $model = null;
	
	public function _initialize()
	{
		parent::_initialize();
		$this->model = new \app\common\model\Goods();
		$config = [
			"isVirtualList" => $this->model->getIsVirtualList(),
			"virtualRefundList" => $this->model->getVirtualRefundList(),
			"isOnSaleList" => $this->model->getIsOnSaleList(),
			"isFreeShippingList" => $this->model->getIsFreeShippingList(),
			"isRecommendList" => $this->model->getIsRecommendList(),
			"isNewList" => $this->model->getIsNewList(),
			"isHotList" => $this->model->getIsHotList(),
			"goodsTypeList" => \app\common\model\Goods::$goodsTypeList,
			'rebateTypeList' => \app\common\model\Goods::$rebateTypeList,
			'levelList' => User::$_level,
		];
		
		$this->assignconfig($config);
		$this->assign($config);
		
	}
	
	/**
	 * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
	 * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
	 * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
	 */
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, true);
			
			
			$total = $this->model
				->with('category,brand,business')
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with('category,brand,business')
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		
		
		$model = new \app\common\model\Goods();
		$countList = $model->countList([]);
	
		return $this->view->fetch('index', [
			'countList' => $countList
		]);
	}
	
	/**
	 * 添加
	 */
	public function add()
	{
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			$spec = $this->request->post("spec/a");
			if ($params) {
				$imgList = $params['images'];
				unset($params['images']);
				
				$attr = isset($params['attr'])?$params['attr']:[];
				unset($params['attr']);
				
				if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
					$params[$this->dataLimitField] = $this->auth->id;
				}
				
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
						$this->model->validate($validate);
					}
					
					if(isset($params['chain_no']) && $params['chain_no']) {
						$goods = $this->model->where(['chain_no' => $params['chain_no']])->find();
						if($goods) {
							throw new Exception('您已经添加了该商品');
						}
					}
					
					$params['input_ids'] = isset($params['input_ids'])?implode(',', $params['input_ids']):'';
					//添加商品
					$result = $this->model->allowField(true)->save($params);
					if (!$result) {
						throw new Exception($this->model->getError());
					}
					
					$goodsId = $this->model->getLastInsId();
					//添加相册
					if ($imgList) {
						$imgRes = $this->model->addImglist($goodsId, $imgList, 1);
						if (!$imgRes) {
							throw new Exception('添加相册出错');
						}
					}
					
					//添加规格
					if($spec){
						$specRes = $this->model->addSpec($goodsId, $spec, 1);
						if(!$specRes){
							throw new Exception('添加规格出错：'.$this->model->getError());
						}
					}
					
					//添加属性
					if($attr){
						$attrRes = $this->model->addAttr($goodsId, $attr,1);
						if(!$attrRes){
							throw new Exception('添加属性出错：'.$this->model->getError());
						}
					}
					
					//添加返利设置
					if($params['rebate_type'] == \app\common\model\Goods::REBATE_ONE) {
						$rebate = $params = $this->request->post("rebate/a");
						$rebate['goods_id'] = $goodsId;
						$rebateRes = Db::name('goodsOneRebate')
							->insert($rebate);
						if(!$rebateRes) {
							throw new Exception('添加返利设置出错');
						}
					}
					
					Db::commit();
					$this->success();
				} catch (\think\exception\PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} catch ( Exception $e){
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", json_encode([]));
		
		//运费模板
		$shippingTemplates = Db::name('shippingTemplate')
			->field('id,name')
			->select();
		
		$cateModel = new \app\common\model\GoodsCategory();
		
		//分类
		$business = Db::name('business')
			->field('id, name')
			->select();
		
		$row = [
			'goods_type' => 1,
			'open_user_grade' => 0,
			'is_on_sale' => 1,
			'is_recommend' => 1,
			'is_new' => 1,
			'is_hot' => 1,
			'is_free_shipping' => 1,
			'rebate_type' => 1,
		];
		
		return $this->view->fetch('add', [
			'categorys' => $cateModel->getTreeCategory(),
			'shippingTemplates' => $shippingTemplates,
			'business' => $business,
			'specs' => [],
			'inputIds' => [],
			'row' => json_encode($row)
		]);
	}
	
	
	/**
	 * 编辑
	 */
	public function edit($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			$spec = $this->request->post("spec/a");
			if ($params) {
				$imgList = $params['images'];
				unset($params['images']);
				
				
				$attr = isset($params['attr'])?$params['attr']:[];
				unset($params['attr']);
				$params['is_on_sale'] = isset($params['is_on_sale'])?$params['is_on_sale']:0;
				$params['is_recommend'] = isset($params['is_recommend'])?$params['is_recommend']:0;
				$params['is_new'] = isset($params['is_new'])?$params['is_new']:0;
				$params['is_hot'] = isset($params['is_hot'])?$params['is_hot']:0;	
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
						$row->validate($validate);
					}
					
					
					$params['input_ids'] = isset($params['input_ids'])?implode(',', $params['input_ids']):'';
					$result = $row->allowField(true)->save($params);
					if ($result === false) {
						throw new Exception($row->getError());
					}
					
					$goodsId = $ids;
					//添加相册
					if ($imgList) {
						$imgRes = $this->model->addImglist($goodsId, $imgList, 2);
						if (!$imgRes) {
							throw new Exception('更改相册出错');
						}
					}
					
					//添加规格
					if($spec){
						$specRes = $this->model->addSpec($goodsId, $spec, 2);
						if(!$specRes){
							throw new Exception('更改规格出错：'.$this->model->getError());
						}
					}

					//添加属性
					if($attr){
						$attrRes = $this->model->addAttr($goodsId, $attr,2);
						if(!$attrRes){
							throw new Exception('更改属性出错：'.$this->model->getError());
						}
					}
					
					//添加返利设置
					if($params['rebate_type'] == \app\common\model\Goods::REBATE_ONE) {
						$rebate = $params = $this->request->post("rebate/a");
						$rebate['goods_id'] = $goodsId;
						$map['goods_id'] = $goodsId;
						$rebateRow = Db::name('goodsOneRebate')->where($map)->find();
						if($rebateRow) {
							$rebateRes = Db::name('goodsOneRebate')
								->where($map)
								->update($rebate);
						} else {
							$rebateRes = Db::name('goodsOneRebate')
								->insert($rebate);
						}
						if($rebateRes === false) {
							throw new Exception('添加返利设置出错');
						}
					}
					
					Db::commit();
					$this->success();
				} catch (\think\exception\PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		//查找相册
		$images = Db::name('goodsImages')->where(['goods_id' => $ids])->column('image_url','id');
		
		$row['images'] = implode(',',$images);
		
		
		
		$cateModel = new \app\common\model\GoodsCategory();
		
		$shippingTemplates = Db::name('shippingTemplate')
			->field('id,name')
			->select();
		
		
		$business = Db::name('business')
			->field('id, name')
			->select();
		
		$specs = [];
		if($row['chain_no']) {
			$specs = Db::name('goodsSpecPrice')
				->where(['goods_id' => $row['id']])
				->select();
		}
		
		//查找商品配置的返利信息
		$rebates = Db::name('goodsOneRebate')
			->where(['goods_id' => $ids])
			->find();
		
		
		return $this->view->fetch('add', [
			'categorys' => $cateModel->getTreeCategory(),
			'row' => $row,
			'shippingTemplates' => $shippingTemplates,
			'business' => $business,
			'specs' => $specs,
			'rebates' => $rebates
		]);
	}
	
	
}
